<template>
  <div class="department-management">
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <div class="search-form">
          <el-form :model="searchForm" inline>
            <el-form-item label="部门名称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入部门名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="上级部门">
              <el-select
                v-model="searchForm.parent_id"
                placeholder="请选择上级部门"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="dept in departmentList"
                  :key="dept._id"
                  :label="dept.name"
                  :value="dept._id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card" shadow="never">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <span class="table-title">部门列表</span>
              <el-tag type="info" size="small">{{ total }} 条记录</el-tag>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="handleAdd" :loading="loading">
                <el-icon><Plus /></el-icon>
                新增部门
              </el-button>
              <el-button @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="departmentList"
          stripe
          border
          style="width: 100%"
          class="department-table"
          row-key="_id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="部门名称" width="200" />
          <el-table-column prop="description" label="部门描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="parent.name" label="上级部门" width="120">
            <template #default="{ row }">
              <el-tag v-if="row.parent?.name" type="primary" size="small">
                {{ row.parent.name }}
              </el-tag>
              <el-tag v-else type="info" size="small">顶级部门</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="level" label="层级" width="80" align="center">
            <template #default="{ row }">
              <el-tag type="warning" size="small">L{{ row.level || 1 }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="team_count" label="团队数量" width="100" align="center">
            <template #default="{ row }">
              <el-tag type="success" size="small">{{ row.team_count || 0 }} 个</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="permission_count" label="权限数量" width="100" align="center">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.permission_count || 0 }} 个</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="success" size="small" @click="handlePermission(row)">
                <el-icon><Setting /></el-icon>
                权限设置
              </el-button>
              <el-button type="warning" size="small" @click="handleTeams(row)">
                <el-icon><User /></el-icon>
                团队管理
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="departmentForm"
        :rules="formRules"
        label-width="100px"
        class="department-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="departmentForm.name"
            placeholder="请输入部门名称"
          />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input
            v-model="departmentForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <el-select
            v-model="departmentForm.parent_id"
            placeholder="请选择上级部门"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="dept in parentDepartmentList"
              :key="dept._id"
              :label="dept.name"
              :value="dept._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number
            v-model="departmentForm.sort_order"
            :min="0"
            :max="999"
            style="width: 100%"
            placeholder="请输入排序号"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="permission-content">
        <div class="permission-info">
          <el-alert
            title="部门权限说明"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>• 部门是权限的顶层，可以设置基础权限</p>
              <p>• 部门权限会向下级部门、团队、角色、用户继承</p>
              <p>• 下级无法覆盖上级的权限设置</p>
            </template>
          </el-alert>
        </div>
        
        <div class="permission-section">
          <h4>部门权限</h4>
          <el-tree
            ref="permissionTreeRef"
            :data="availablePermissions"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            show-checkbox
            default-expand-all
            :default-checked-keys="currentDepartmentPermissions"
            class="permission-tree"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit" :loading="submitLoading">
            保存权限
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Setting, User } from '@element-plus/icons-vue'
import type { departmentInfoData } from '@/api/department/type'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const permissionTreeRef = ref()
const departmentList = ref<departmentInfoData[]>([])
const parentDepartmentList = ref<departmentInfoData[]>([])
const total = ref(0)
const currentDepartment = ref<departmentInfoData | null>(null)
const currentDepartmentPermissions = ref<string[]>([])
const availablePermissions = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  name: '',
  parent_id: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  size: 10
})

// 部门表单
const departmentForm = reactive<departmentInfoData>({
  _id: '',
  name: '',
  description: '',
  parent_id: '',
  level: 1,
  sort_order: 0,
  team_count: 0,
  permission_count: 0
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑部门' : '新增部门')

// 方法
const loadDepartmentList = async () => {
  loading.value = true
  try {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 死数据 - 树形结构
    const mockData: departmentInfoData[] = [
      {
        _id: '1',
        name: '技术部',
        description: '负责公司技术开发和维护',
        parent_id: '',
        level: 1,
        sort_order: 1,
        team_count: 2,
        permission_count: 8,
        permissions: ['user:read', 'user:write', 'role:read', 'team:read'],
        create_time: Date.now() - 86400000 * 30,
        children: [
          {
            _id: '1-1',
            name: '前端开发组',
            description: '负责前端开发',
            parent_id: '1',
            level: 2,
            sort_order: 1,
            team_count: 1,
            permission_count: 6,
            permissions: ['user:read', 'role:read'],
            create_time: Date.now() - 86400000 * 20
          },
          {
            _id: '1-2',
            name: '后端开发组',
            description: '负责后端开发',
            parent_id: '1',
            level: 2,
            sort_order: 2,
            team_count: 1,
            permission_count: 6,
            permissions: ['user:read', 'role:read'],
            create_time: Date.now() - 86400000 * 15
          }
        ]
      },
      {
        _id: '2',
        name: '市场部',
        description: '负责市场推广和品牌建设',
        parent_id: '',
        level: 1,
        sort_order: 2,
        team_count: 1,
        permission_count: 4,
        permissions: ['user:read', 'market:write'],
        create_time: Date.now() - 86400000 * 25
      },
      {
        _id: '3',
        name: '人事部',
        description: '负责人力资源管理',
        parent_id: '',
        level: 1,
        sort_order: 3,
        team_count: 1,
        permission_count: 6,
        permissions: ['user:read', 'user:write', 'hr:write'],
        create_time: Date.now() - 86400000 * 20
      },
      {
        _id: '4',
        name: '财务部',
        description: '负责财务管理',
        parent_id: '',
        level: 1,
        sort_order: 4,
        team_count: 1,
        permission_count: 5,
        permissions: ['user:read', 'finance:write'],
        create_time: Date.now() - 86400000 * 15
      }
    ]
    
    departmentList.value = mockData
    parentDepartmentList.value = mockData.filter(dept => !dept.parent_id) // 只显示顶级部门作为父级选项
    total.value = mockData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取部门列表失败')
  } finally {
    loading.value = false
  }
}

const loadPermissions = () => {
  // 模拟权限树数据
  availablePermissions.value = [
    {
      id: 'system-permissions',
      name: '系统管理权限',
      children: [
        { id: 'user:read', name: '用户查看' },
        { id: 'user:write', name: '用户编辑' },
        { id: 'user:delete', name: '用户删除' },
        { id: 'role:read', name: '角色查看' },
        { id: 'role:write', name: '角色编辑' },
        { id: 'role:delete', name: '角色删除' },
        { id: 'team:read', name: '团队查看' },
        { id: 'team:write', name: '团队编辑' },
        { id: 'team:delete', name: '团队删除' },
        { id: 'department:read', name: '部门查看' },
        { id: 'department:write', name: '部门编辑' },
        { id: 'department:delete', name: '部门删除' }
      ]
    },
    {
      id: 'business-permissions',
      name: '业务权限',
      children: [
        { id: 'market:write', name: '市场管理' },
        { id: 'hr:write', name: '人事管理' },
        { id: 'finance:write', name: '财务管理' },
        { id: 'project:write', name: '项目管理' }
      ]
    }
  ]
}

const handleSearch = () => {
  pagination.page = 1
  loadDepartmentList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    parent_id: ''
  })
  pagination.page = 1
  loadDepartmentList()
}

const handleRefresh = () => {
  loadDepartmentList()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: departmentInfoData) => {
  isEdit.value = true
  Object.assign(departmentForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row: departmentInfoData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除部门 "${row.name}" 吗？删除后其下级部门也将被删除！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('删除成功')
    loadDepartmentList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handlePermission = (row: departmentInfoData) => {
  currentDepartment.value = row
  currentDepartmentPermissions.value = row.permissions || []
  permissionDialogVisible.value = true
}

const handleTeams = (row: departmentInfoData) => {
  ElMessage.info('团队管理功能开发中...')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
    dialogVisible.value = false
    loadDepartmentList()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handlePermissionSubmit = async () => {
  try {
    submitLoading.value = true
    
    // 获取选中的权限
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || []
    const halfCheckedKeys = permissionTreeRef.value?.getHalfCheckedKeys() || []
    const allPermissions = [...checkedKeys, ...halfCheckedKeys]
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
    loadDepartmentList()
  } catch (error: any) {
    ElMessage.error('权限设置失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(departmentForm, {
    _id: '',
    name: '',
    description: '',
    parent_id: '',
    level: 1,
    sort_order: 0,
    team_count: 0,
    permission_count: 0
  })
  formRef.value?.clearValidate()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadDepartmentList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadDepartmentList()
}

const formatTime = (timestamp?: number) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadDepartmentList()
  loadPermissions()
})
</script>

<style scoped lang='scss'>
.department-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .search-section {
    margin-bottom: 20px;
    
    .search-card {
      border-radius: 12px;
      border: none;
      
      .search-form {
        .el-form-item {
          margin-bottom: 16px;
        }
      }
    }
  }

  .table-section {
    .table-card {
      border-radius: 12px;
      border: none;
      
      .table-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-left {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .table-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
          }
        }
        
        .header-right {
          display: flex;
          gap: 12px;
        }
      }
      
      .department-table {
        margin-bottom: 20px;
        
        :deep(.el-table__header) {
          background-color: #fafafa;
        }
        
        :deep(.el-table__row:hover) {
          background-color: #f5f7fa;
        }
      }
      
      .pagination-wrapper {
        display: flex;
        justify-content: center;
        padding-top: 20px;
      }
    }
  }
}

.department-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.permission-content {
  .permission-info {
    margin-bottom: 20px;
  }
  
  .permission-section {
    h4 {
      margin-bottom: 12px;
      color: #303133;
      font-weight: 600;
    }
    
    .permission-tree {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 12px;
      max-height: 400px;
      overflow-y: auto;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .department-management {
    padding: 10px;
    
    .search-section .search-card .search-form {
      .el-form-item {
        display: block;
        margin-bottom: 12px;
        
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
    
    .table-section .table-card .table-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
  }
}
</style>
